package me.zhengjie.inter.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.BisQyRow;
import me.zhengjie.business.domain.Snry;
import me.zhengjie.business.repository.BisQyRowRepository;
import me.zhengjie.business.repository.SnryRepository;
import me.zhengjie.business.repository.ZhsqRepository;
import me.zhengjie.business.service.dto.BisQyRowDto;
import me.zhengjie.business.service.dto.SnryDto;
import me.zhengjie.business.service.dto.SnryQueryCriteria;
import me.zhengjie.business.service.mapstruct.SnryMapper;
import me.zhengjie.config.TreeBuilder;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.inter.service.MpSnryService;
import me.zhengjie.repository.LocalStorageRepository;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @description 服务接口
 * @author xiahongbo
 * @date 2022-07-10
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class MpSnryServiceImpl implements MpSnryService {

    private final LocalStorageRepository localStorageRepository;
    private final SnryRepository snryRepository;
    private final SnryMapper snryMapper;

    private final BisQyRowRepository qyRowRepository;
    private final ZhsqRepository zhsqRepository;




    @Override
    public Map<String, Object> queryAll(SnryQueryCriteria criteria, Pageable pageable) {
        log.info("移动端[MpSnryServiceImpl - queryAll]分页查询失能人员 {} ", criteria);
        criteria.setSfyx("1");
        Page<Snry> page = snryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(snryMapper::toDto));
    }

    @Override
    public List<SnryDto> queryAll(SnryQueryCriteria criteria) {
        log.info("移动端[MpSnryServiceImpl - queryAll]查询失能人员 {} ", criteria);
        criteria.setSfyx("1");
        List<SnryDto> list = snryMapper.toDto(snryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
        return list;
    }

    @Override
    public SnryDto findById(String bisSnryId) {
        Snry snry = snryRepository.findById(bisSnryId).orElseGet(Snry::new);
        ValidationUtil.isNull(snry.getBisSnryId(),"Snry","bisSnryId",bisSnryId);
        return snryMapper.toDto(snry);
    }

    @Override
    public SnryDto create(Snry resources, String ids) {
        Long userId = SecurityUtils.getCurrentUserId();
        Snry isExist = snryRepository.queryByBisSnrySfzAndBisSnryUserIdAndSfyx(resources.getBisSnrySfz(), userId, "1");
        if(isExist != null) {
            throw new BadRequestException("失能人员["+resources.getBisSnryXm()+"]已经存在");
        }

        resources.setBisSnryId(IdUtil.simpleUUID());
        resources.setBisSnryUserId(userId);
        SnryDto snryDto = snryMapper.toDto(snryRepository.save(resources));
        log.info("移动端[MpSnryServiceImpl - create]新增失能人员 {} ", snryDto);
        log.info("移动端[MpSnryServiceImpl - create]新增失能人员图片 {} ", ids);
        // 新增照片

        if(ids != null && !ids.equals("")){

            String[] picIds = ids.split(",");
            for (String picId:picIds) {

                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(snryDto.getBisSnryId()));
                localStorageRepository.save(localStorage);
            }
        }
        return snryDto;
    }

    @Override
    @Transactional
    public SnryDto update(Snry resources, String ids) {
        SnryDto snryDto = snryMapper.toDto(snryRepository.save(resources));
        zhsqRepository.updateJbxx(resources.getBisSnryXm(), resources.getBisSnrySfz(), resources.getBisSnryHldzSsqx(), resources.getBisSnryHldzXxdz(), resources.getBisSnryHldz(),
                resources.getBisSnryLxdh(), resources.getBisSnryJhrdh(), resources.getBisSnryId());
        log.info("移动端[MpSnryServiceImpl - update]修改失能人员 {} ", snryDto);
        log.info("移动端[MpSnryServiceImpl - update]修改失能人员图片 {} ", ids);
        if(ids != null && !ids.equals("")){
            String[] picIds = ids.split(",");
            for (String picId:picIds) {
                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(snryDto.getBisSnryId()));
                localStorageRepository.save(localStorage);
            }
        }
        return snryDto;
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String bisSnryId : ids) {
            SnryDto snryDto = findById(bisSnryId);
            Snry snry = snryMapper.toEntity(snryDto);
            snry.setSfyx("0");
            log.info("移动端[MpSnryServiceImpl - deleteAll]删除失能人员 {} ", bisSnryId);
            log.info("移动端[MpSnryServiceImpl - deleteAll]删除失能人员 {} ", snryDto.getBisSnryXm());
            snryRepository.save(snry);
        }
    }

    @Override
    public JSONArray queryQyJd() {
        List<BisQyRow> qyRowList = qyRowRepository.findAll(Sort.by(Sort.Direction.ASC,"bisQyRowId"));
        List<BisQyRowDto> list = new ArrayList<>();
        qyRowList.forEach(x->{
            BisQyRowDto rowDto = new BisQyRowDto();
            rowDto.setBisQyRowId(x.getBisQyRowId());
            rowDto.setBisQyPid(x.getBisQyPid());
            rowDto.setBisQyName(x.getBisQyName());
            list.add(rowDto);
        });
        TreeBuilder treeBuilder = new TreeBuilder();
        JSONArray permJsonArray = treeBuilder.buildTree(list);
        return permJsonArray;
    }

    @Override
    public JSONArray queryQyJd(String bz) {
        List<BisQyRow> qyRowList = qyRowRepository.findByBzAndSfyxOrderByBisQyPid("03", "1");
        List<BisQyRowDto> list = new ArrayList<>();
        qyRowList.forEach(x->{
            BisQyRowDto rowDto = new BisQyRowDto();
            rowDto.setBisQyRowId(x.getBisQyRowId());
            rowDto.setBisQyPid(x.getBisQyPid());
            rowDto.setBisQyName(x.getBisQyName());
            list.add(rowDto);
        });
        TreeBuilder treeBuilder = new TreeBuilder();
        JSONArray permJsonArray = treeBuilder.buildTree(list);
        return permJsonArray;
    }

    @Override
    public Integer checkCreate(Long userId) {
        return snryRepository.checkAddSnry(userId);
    }
}
